<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>蔬记 - 种植日志</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#8BC34A',
                        light: '#E8F5E9',
                        dark: '#33691E',
                        neutral: '#F5F5F5',
                        textPrimary: '#333333',
                        textSecondary: '#666666',
                        textLight: '#999999',
                    },
                    fontFamily: {
                        sans: ['PingFang SC', 'Microsoft YaHei', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-card {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            }
            .tab-active {
                @apply text-primary border-b-2 border-primary;
            }
            .log-type-bg {
                @apply bg-light text-primary text-xs font-medium px-2 py-0.5 rounded-full;
            }
        }
    </style>
</head>
<body class="bg-green-50 font-sans text-textPrimary">
    <!-- 顶部导航栏 -->
    <div class="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm flex items-center justify-between px-4 z-30">
        <button class="back-btn p-2 -ml-2" onclick="goBack()">
            <i class="fa fa-chevron-left text-textPrimary"></i>
        </button>
        <h1 class="nav-title text-lg font-semibold">种植日志</h1>
        <div class="nav-spacer w-8"></div>
    </div>

    <!-- 页面容器 -->
    <div class="page-container pt-16 pb-24 min-h-screen">
        <!-- 页面头部和统计信息 -->
        <div class="page-header px-4 py-6 bg-white">
            <div class="header-content">
                <h2 class="page-title text-xl font-bold">我的种植记录</h2>
                <p class="page-subtitle text-textSecondary mt-1 text-sm">记录每一次与植物的互动，见证生长的每一步</p>
                <div class="log-stats grid grid-cols-3 gap-4 mt-4">
                    <div class="stat-item flex flex-col items-center">
                        <div class="stat-number text-2xl font-bold" id="totalLogs">0</div>
                        <div class="stat-label text-textLight text-xs mt-1">日志总数</div>
                    </div>
                    <div class="stat-item flex flex-col items-center">
                        <div class="stat-number text-2xl font-bold" id="thisWeekLogs">0</div>
                        <div class="stat-label text-textLight text-xs mt-1">本周新增</div>
                    </div>
                    <div class="stat-item flex flex-col items-center">
                        <div class="stat-number text-2xl font-bold" id="activePlants">0</div>
                        <div class="stat-label text-textLight text-xs mt-1">活跃植物</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-section px-4 py-3 bg-white mt-2">
            <div class="search-box relative flex items-center bg-neutral rounded-full px-4 py-2">
                <i class="fa fa-search text-textLight absolute left-4"></i>
                <input type="text" class="search-input bg-transparent w-full pl-8 text-sm focus:outline-none" placeholder="搜索日志内容..." oninput="searchLogs(this.value)">
            </div>
        </div>

        <!-- 过滤标签栏 -->
        <div class="filter-tabs overflow-x-auto whitespace-nowrap px-4 py-3 bg-white mt-2">
            <div class="inline-flex space-x-3">
                <div class="filter-tab tab-active whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium" data-type="all" onclick="filterLogs('all')">全部</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="浇水" onclick="filterLogs('浇水')">浇水</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="施肥" onclick="filterLogs('施肥')">施肥</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="修剪" onclick="filterLogs('修剪')">修剪</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="病虫害" onclick="filterLogs('病虫害')">病虫害</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="收获" onclick="filterLogs('收获')">收获</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="日常护理" onclick="filterLogs('日常护理')">日常护理</div>
                <div class="filter-tab whitespace-nowrap px-4 py-1.5 rounded-full text-sm font-medium text-textSecondary" data-type="开花结果" onclick="filterLogs('开花结果')">开花结果</div>
            </div>
        </div>

        <!-- 日志列表区域 -->
        <div class="page active" id="logs-page" class="px-4 py-3 space-y-4">
            <!-- 日志列表将通过JavaScript动态生成 -->
        </div>

        <!-- 添加日志按钮 -->
        <button class="add-log-btn fixed right-6 bottom-32 w-14 h-14 bg-primary text-white rounded-full shadow-lg flex items-center justify-center z-20" onclick="showAddLogModal()">
            <i class="fa fa-plus text-xl"></i>
        </button>
    </div>

    <!-- 添加日志模态框 -->
    <div id="addLogModal" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300">
        <div class="modal-container bg-white rounded-2xl w-[90%] max-w-md overflow-hidden transform transition-transform duration-300 translate-y-8">
            <div class="modal-content">
                <div class="modal-header flex items-center justify-between px-5 py-4 border-b border-gray-100">
                    <h3 class="modal-title text-lg font-semibold">添加种植日志</h3>
                    <button class="modal-close p-2 -mr-2 text-textLight" onclick="hideAddLogModal()">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <form id="logForm" onsubmit="addNewLog(event)" class="p-5">
                    <div class="form-group mb-4">
                        <label for="plantName" class="block text-sm font-medium text-textSecondary mb-1">植物名称</label>
                        <input type="text" id="plantName" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" required>
                    </div>
                    <div class="form-group mb-4">
                        <label class="block text-sm font-medium text-textSecondary mb-2">操作类型</label>
                        <div class="log-type-checkboxes grid grid-cols-3 gap-2">
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="浇水" class="hidden">
                                <span class="text-sm">浇水</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="施肥" class="hidden">
                                <span class="text-sm">施肥</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="修剪" class="hidden">
                                <span class="text-sm">修剪</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="病虫害" class="hidden">
                                <span class="text-sm">病虫害</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="收获" class="hidden">
                                <span class="text-sm">收获</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light">
                                <input type="checkbox" name="logTypes" value="日常护理" class="hidden">
                                <span class="text-sm">日常护理</span>
                            </label>
                            <label class="checkbox-label flex items-center justify-center p-2 border border-gray-200 rounded-lg cursor-pointer transition-all hover:border-primary hover:bg-light col-span-3">
                                <input type="checkbox" name="logTypes" value="开花结果" class="hidden">
                                <span class="text-sm">开花结果</span>
                            </label>
                        </div>
                    </div>
                    <div class="form-group mb-6">
                        <label for="logContent" class="block text-sm font-medium text-textSecondary mb-1">详细记录</label>
                        <textarea id="logContent" rows="4" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none" required></textarea>
                    </div>
                    <div class="form-actions flex space-x-3">
                        <button type="button" class="btn-secondary flex-1 px-4 py-2.5 border border-gray-200 rounded-lg text-textSecondary font-medium transition-colors hover:bg-gray-50" onclick="hideAddLogModal()">取消</button>
                        <button type="submit" class="btn-primary flex-1 px-4 py-2.5 bg-primary text-white rounded-lg font-medium transition-colors hover:bg-dark">保存日志</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Toast 提示 -->
    <div id="toast" class="fixed top-1/4 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-textPrimary text-white px-4 py-2 rounded-lg shadow-lg opacity-0 transition-opacity duration-300 z-50">操作成功</div>

    <!-- 底部导航Tab -->
    <div class="fixed bottom-0 left-0 right-0 h-16 bg-white border-t border-gray-100 flex items-center justify-around z-30">
        <a href="index.html" class="tab-item flex flex-col items-center justify-center text-textLight">
            <i class="fa fa-home text-xl"></i>
            <span class="text-xs mt-0.5">首页</span>
        </a>
        <a href="growing-plants.html" class="tab-item flex flex-col items-center justify-center text-textLight">
            <i class="fa fa-leaf text-xl"></i>
            <span class="text-xs mt-0.5">菜园</span>
        </a>
        <a href="profile.html" class="tab-item flex flex-col items-center justify-center text-textLight">
            <i class="fa fa-user text-xl"></i>
            <span class="text-xs mt-0.5">我的</span>
        </a>
    </div>

    <script>
        function goBack() { window.history.back(); }

        // 兼容详情页写入的对象结构与本页数组结构
        function normalizeStoredLogs() {
            const raw = localStorage.getItem('plantLogs');
            if (!raw) return [];
            try {
                const data = JSON.parse(raw);
                if (Array.isArray(data)) return data;
                if (data && typeof data === 'object') {
                    const result = [];
                    Object.keys(data).forEach(pid => {
                        const entries = Array.isArray(data[pid]) ? data[pid] : [];
                        entries.forEach(entry => {
                            const t = entry.actionTime || entry.createdAt || new Date().toISOString();
                            const d = new Date(t);
                            const yyyy = d.getFullYear();
                            const mm = String(d.getMonth() + 1).padStart(2, '0');
                            const dd = String(d.getDate()).padStart(2, '0');
                            const hh = String(d.getHours()).padStart(2, '0');
                            const mi = String(d.getMinutes()).padStart(2, '0');
                            const typeMap = { '浇水': '浇水', '施肥': '施肥', '修剪': '修剪', '病虫防治': '病虫害', '松土': '日常护理', '收获': '收获' };
                            result.push({
                                id: entry.id || Date.now(),
                                plant: entry.plantName || '',
                                date: `${yyyy}-${mm}-${dd}`,
                                time: `${hh}:${mi}`,
                                content: entry.remark && entry.remark.trim() ? entry.remark : `${entry.actionLabel || '操作'}（自动记录）`,
                                type: typeMap[entry.actionLabel] || '日常护理',
                                createdAt: entry.createdAt || t
                            });
                        });
                    });
                    return result.sort((a, b) => new Date(`${b.date}T${b.time}:00`) - new Date(`${a.date}T${a.time}:00`));
                }
            } catch (e) { return []; }
            return [];
        }

        function groupLogsByDate(list) {
            const grouped = {};
            list.forEach(l => {
                if (!grouped[l.date]) grouped[l.date] = [];
                grouped[l.date].push(l);
            });
            return grouped;
        }

        function formatDateLabel(date) {
            const today = new Date().toISOString().split('T')[0];
            const yesterday = new Date(Date.now() - 24*60*60*1000).toISOString().split('T')[0];
            if (date === today) return '今天';
            if (date === yesterday) return '昨天';
            const d = new Date(date);
            return `${d.getMonth() + 1}月${d.getDate()}日`;
        }

        // 获取操作类型对应的图标
        function getTypeIcon(type) {
            const iconMap = {
                '浇水': 'fa-tint',
                '施肥': 'fa-flask',
                '修剪': 'fa-scissors',
                '病虫害': 'fa-bug',
                '收获': 'fa-gift',
                '日常护理': 'fa-heart',
                '开花结果': 'fa-leaf'
            };
            return iconMap[type] || 'fa-pencil';
        }

        // 获取操作类型对应的颜色
        function getTypeColor(type) {
            const colorMap = {
                '浇水': 'bg-blue-100 text-blue-600',
                '施肥': 'bg-yellow-100 text-yellow-600',
                '修剪': 'bg-purple-100 text-purple-600',
                '病虫害': 'bg-red-100 text-red-600',
                '收获': 'bg-orange-100 text-orange-600',
                '日常护理': 'bg-green-100 text-green-600',
                '开花结果': 'bg-pink-100 text-pink-600'
            };
            return colorMap[type] || 'bg-gray-100 text-gray-600';
        }

        // 渲染日志列表
        function renderLogs(logs) {
            const container = document.getElementById('logs-page');
            container.innerHTML = '';
            
            // 如果没有传入日志，则从localStorage获取
            if (!logs) logs = normalizeStoredLogs();
            
            updateStats(logs);
            
            if (!logs.length) {
                showEmptyState(container);
                return;
            }
            
            const grouped = groupLogsByDate(logs);
            const dates = Object.keys(grouped).sort((a, b) => new Date(b) - new Date(a));
            
            dates.forEach(date => {
                // 日期标题
                const dateHeader = document.createElement('div');
                dateHeader.className = 'log-date text-center py-3 text-textSecondary text-sm';
                dateHeader.textContent = formatDateLabel(date);
                container.appendChild(dateHeader);
                
                // 日志列表
                const items = grouped[date].slice().sort((a, b) => new Date(`${b.date}T${b.time}:00`) - new Date(`${a.date}T${a.time}:00`));
                items.forEach(item => {
                    const el = document.createElement('div');
                    el.className = 'log-item bg-white rounded-xl p-4 shadow-card opacity-0 transform translate-y-10 transition-all duration-300';
                    el.setAttribute('data-type', item.type);
                    el.setAttribute('data-plant', item.plant);
                    el.setAttribute('data-content', item.content);
                    
                    const typeIcon = getTypeIcon(item.type);
                    const typeColor = getTypeColor(item.type);
                    
                    el.innerHTML = `
                        <div class="log-header flex justify-between items-start">
                            <div class="log-plant flex items-center">
                                <i class="fa ${typeIcon} mr-2 text-primary"></i>
                                <span class="font-medium">${item.plant}</span>
                            </div>
                            <div class="log-time text-textLight text-xs">${item.time}</div>
                        </div>
                        <div class="log-content mt-2 text-sm leading-relaxed">${item.content}</div>
                        <div class="log-meta flex justify-between items-center mt-3">
                            <span class="log-type ${typeColor} text-xs font-medium px-2 py-0.5 rounded-full">${item.type}</span>
                            <div class="log-actions flex items-center space-x-3">
                                <button class="btn-icon text-textLight hover:text-primary transition-colors" onclick="editLog(${item.id})"><i class="fa fa-pencil"></i></button>
                                <button class="btn-icon text-textLight hover:text-red-500 transition-colors" onclick="deleteLog(${item.id})"><i class="fa fa-trash-o"></i></button>
                            </div>
                        </div>
                    `;
                    
                    container.appendChild(el);
                    
                    // 触发动画 - 使用requestAnimationFrame确保DOM已更新
                    requestAnimationFrame(() => {
                        el.style.opacity = '1';
                        el.style.transform = 'translateY(0)';
                    });
                });
            });
        }

        // 仅当没有任何日志数据时，注入一组演示数据用于预览
        function seedDemoLogsIfEmpty() {
            const existing = normalizeStoredLogs();
            if (existing && existing.length > 0) return;
            const now = new Date();
            function dOffset(days) {
                const d = new Date(now);
                d.setDate(d.getDate() - days);
                const yyyy = d.getFullYear();
                const mm = String(d.getMonth() + 1).padStart(2, '0');
                const dd = String(d.getDate()).padStart(2, '0');
                return `${yyyy}-${mm}-${dd}`;
            }
            function log(id, plant, date, time, content, type) {
                return { id, plant, date, time, content, type, createdAt: `${date}T${time}:00` };
            }
            const demo = [
                log(Date.now()-1000, '番茄（樱桃）', dOffset(0), '08:30', '清晨浇水，叶片精神。', '浇水'),
                log(Date.now()-900, '番茄（樱桃）', dOffset(0), '12:10', '喷施叶面肥，稀释比例1:800。', '施肥'),
                log(Date.now()-800, '生菜（罗马）', dOffset(0), '19:05', '检查叶面，未发现病虫害。', '日常护理'),
                log(Date.now()-700, '黄瓜（旱黄）', dOffset(1), '07:50', '松土透气，根系更旺盛。', '日常护理'),
                log(Date.now()-600, '黄瓜（旱黄）', dOffset(1), '18:20', '修剪老叶，改善通风透光。', '修剪'),
                log(Date.now()-500, '辣椒（小米辣）', dOffset(1), '20:15', '少量追肥，促进开花。', '施肥'),
                log(Date.now()-400, '生菜（奶油）', dOffset(2), '09:10', '早间浇水，保持基质湿润。', '浇水'),
                log(Date.now()-300, '番茄（樱桃）', dOffset(2), '10:45', '发现2朵新花，轻轻摇晃授粉。', '开花结果'),
                log(Date.now()-200, '生菜（罗马）', dOffset(2), '16:30', '外叶可采收，口感鲜嫩。', '收获'),
                log(Date.now()-100, '辣椒（小米辣）', dOffset(3), '14:00', '叶面有少量蚜虫，喷洒低毒药剂。', '病虫害')
            ];
            localStorage.setItem('plantLogs', JSON.stringify(demo));
        }
        
        function updateStats(logs) {
            const totalEl = document.getElementById('totalLogs');
            const weekEl = document.getElementById('thisWeekLogs');
            const activeEl = document.getElementById('activePlants');
            if (totalEl) totalEl.textContent = logs.length;
            if (weekEl) weekEl.textContent = countThisWeek(logs);
            if (activeEl) activeEl.textContent = countActivePlants(logs);
        }
        
        function countThisWeek(logs) {
            const now = new Date();
            const day = now.getDay();
            const start = new Date(now);
            start.setHours(0,0,0,0);
            start.setDate(start.getDate() - day);
            return logs.filter(l => new Date(l.date) >= start).length;
        }
        
        function countActivePlants(logs) {
            const s = new Set();
            logs.forEach(l => s.add(l.plant || ''));
            s.delete('');
            return s.size;
        }

        function showEmptyState(container) {
            const empty = document.createElement('div');
            empty.className = 'empty-state flex flex-col items-center justify-center py-16 text-center';
            empty.innerHTML = `
                <div class="empty-icon text-6xl mb-4 text-primary/20"><i class="fa fa-book"></i></div>
                <div class="empty-title text-lg font-medium mb-2">还没有种植日志</div>
                <div class="empty-desc text-textLight text-sm mb-6">点击右下角的按钮记录你的第一条日志吧！</div>
                <button class="add-first-log-btn px-6 py-2.5 bg-primary text-white rounded-full shadow-sm font-medium transition-colors hover:bg-dark" onclick="showAddLogModal()">
                    <i class="fa fa-plus mr-1"></i> 添加第一条日志
                </button>
            `;
            container.appendChild(empty);
        }

        // 搜索日志功能
        function searchLogs(keyword) {
            const logs = normalizeStoredLogs();
            if (!keyword.trim()) {
                renderLogs();
                // 重置过滤标签
                resetFilterTabs();
                return;
            }
            
            const filtered = logs.filter(log => 
                log.plant.toLowerCase().includes(keyword.toLowerCase()) ||
                log.content.toLowerCase().includes(keyword.toLowerCase()) ||
                log.type.toLowerCase().includes(keyword.toLowerCase())
            );
            
            renderLogs(filtered);
        }

        // 重置过滤标签
        function resetFilterTabs() {
            const tabs = document.querySelectorAll('.filter-tab');
            tabs.forEach(tab => {
                if (tab.dataset.type === 'all') {
                    tab.classList.add('tab-active');
                    tab.classList.remove('text-textSecondary');
                } else {
                    tab.classList.remove('tab-active');
                    tab.classList.add('text-textSecondary');
                }
            });
        }

        // 过滤日志功能
        function filterLogs(type) {
            // 更新选中状态
            const tabs = document.querySelectorAll('.filter-tab');
            tabs.forEach(tab => {
                if (tab.dataset.type === type) {
                    tab.classList.add('tab-active');
                    tab.classList.remove('text-textSecondary');
                } else {
                    tab.classList.remove('tab-active');
                    tab.classList.add('text-textSecondary');
                }
            });
            
            const logs = normalizeStoredLogs();
            if (type === 'all') {
                renderLogs();
                // 清空搜索框
                document.querySelector('.search-input').value = '';
                return;
            }
            
            // 支持多类型日志的过滤
            const filtered = logs.filter(log => {
                // 如果日志类型包含逗号（多个类型），检查是否包含当前类型
                if (log.type.includes(',')) {
                    const types = log.type.split(',').map(t => t.trim());
                    return types.includes(type);
                }
                // 单一类型，直接匹配
                return log.type === type;
            });
            
            renderLogs(filtered);
        }

        // 显示添加日志模态框
        function showAddLogModal() {
            const modal = document.getElementById('addLogModal');
            modal.classList.remove('opacity-0', 'pointer-events-none');
            // 重置模态框位置
            modal.querySelector('.modal-container').classList.remove('translate-y-8');
            
            // 清空表单
            document.getElementById('logForm').reset();
            
            // 初始化复选框样式处理
            initCheckboxStyling();
            
            // 阻止页面滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 初始化复选框样式处理
        function initCheckboxStyling() {
            const checkboxes = document.querySelectorAll('input[name="logTypes"]');
            
            // 更新现有复选框的样式
            checkboxes.forEach(checkbox => {
                updateCheckboxStyle(checkbox);
                
                // 移除已存在的事件监听器，避免重复添加
                const newCheckbox = checkbox.cloneNode(true);
                checkbox.parentNode.replaceChild(newCheckbox, checkbox);
                
                // 添加新的事件监听器
                newCheckbox.addEventListener('change', function() {
                    updateCheckboxStyle(this);
                });
            });
        }
        
        // 更新单个复选框的样式
        function updateCheckboxStyle(checkbox) {
            const label = checkbox.closest('.checkbox-label');
            if (label) {
                if (checkbox.checked) {
                    label.classList.add('border-primary', 'bg-light');
                } else {
                    label.classList.remove('border-primary', 'bg-light');
                }
            }
        }

        // 隐藏添加日志模态框
        function hideAddLogModal() {
            const modal = document.getElementById('addLogModal');
            modal.classList.add('opacity-0', 'pointer-events-none');
            // 添加动画
            modal.querySelector('.modal-container').classList.add('translate-y-8');
            
            // 恢复页面滚动
            document.body.style.overflow = '';
        }

        // 添加新日志
        function addNewLog(event) {
            event.preventDefault();
            
            const plantName = document.getElementById('plantName').value;
            // 获取选中的所有操作类型
            const selectedTypes = Array.from(document.querySelectorAll('input[name="logTypes"]:checked'))
                                      .map(checkbox => checkbox.value)
                                      .join(', ');
            
            if (!selectedTypes) {
                showToast('请至少选择一种操作类型！');
                return;
            }
            
            const logContent = document.getElementById('logContent').value;
            
            const now = new Date();
            const yyyy = now.getFullYear();
            const mm = String(now.getMonth() + 1).padStart(2, '0');
            const dd = String(now.getDate()).padStart(2, '0');
            const hh = String(now.getHours()).padStart(2, '0');
            const mi = String(now.getMinutes()).padStart(2, '0');
            
            const newLog = {
                id: Date.now(),
                plant: plantName,
                date: `${yyyy}-${mm}-${dd}`,
                time: `${hh}:${mi}`,
                content: logContent,
                type: selectedTypes,
                createdAt: now.toISOString()
            };
            
            // 保存到localStorage
            const logs = normalizeStoredLogs();
            logs.unshift(newLog); // 添加到开头
            localStorage.setItem('plantLogs', JSON.stringify(logs));
            
            // 关闭模态框
            hideAddLogModal();
            
            // 重新渲染日志
            renderLogs();
            
            // 显示提示
            showToast('日志添加成功！');
        }

        // 编辑日志（简单版，点击后打开添加框）
        function editLog(id) {
            const logs = normalizeStoredLogs();
            const log = logs.find(l => l.id === id);
            if (log) {
                document.getElementById('plantName').value = log.plant;
                
                // 清空所有复选框
                document.querySelectorAll('input[name="logTypes"]').forEach(checkbox => {
                    checkbox.checked = false;
                });
                
                // 根据日志类型设置选中的复选框
                // 如果是多选类型（包含逗号）
                if (log.type.includes(',')) {
                    const types = log.type.split(',').map(t => t.trim());
                    types.forEach(type => {
                        const checkbox = document.querySelector(`input[name="logTypes"][value="${type}"]`);
                        if (checkbox) checkbox.checked = true;
                    });
                } else {
                    // 单一类型
                    const checkbox = document.querySelector(`input[name="logTypes"][value="${log.type}"]`);
                    if (checkbox) checkbox.checked = true;
                }
                
                document.getElementById('logContent').value = log.content;
                showAddLogModal();
                // 初始化复选框样式
                initCheckboxStyling();
                // 删除原日志
                const index = logs.findIndex(l => l.id === id);
                logs.splice(index, 1);
                localStorage.setItem('plantLogs', JSON.stringify(logs));
            }
        }

        // 删除日志
        function deleteLog(id) {
            if (confirm('确定要删除这条日志吗？')) {
                const logs = normalizeStoredLogs();
                const filtered = logs.filter(l => l.id !== id);
                localStorage.setItem('plantLogs', JSON.stringify(filtered));
                renderLogs();
                showToast('日志已删除');
            }
        }

        // 显示提示信息
        function showToast(message) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.classList.add('opacity-100');
            setTimeout(() => {
                toast.classList.remove('opacity-100');
            }, 2000);
        }

        // 点击模态框外部关闭
        document.getElementById('addLogModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('addLogModal')) {
                hideAddLogModal();
            }
        });

        document.addEventListener('DOMContentLoaded', () => {
            seedDemoLogsIfEmpty();
            renderLogs();
        });
    </script>
    
    <!-- 底部导航Tab -->
    <nav class="tab-bar fixed bottom-0 left-0 right-0 flex items-center justify-around py-2 border-t border-gray-200 bg-white">
        <a href="home.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-home text-lg"></i>
            <span class="text-xs mt-1">首页</span>
        </a>
        <a href="growing-plants.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-leaf text-lg"></i>
            <span class="text-xs mt-1">菜园</span>
        </a>
        <a href="task.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-tasks text-lg"></i>
            <span class="text-xs mt-1">任务</span>
        </a>
        <a href="reminders.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-bell text-lg"></i>
            <span class="text-xs mt-1">提醒</span>
        </a>
        <a href="profile.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-user text-lg"></i>
            <span class="text-xs mt-1">我的</span>
        </a>
    </nav>
</body>
</html>